package com.sgb.kjwl.view.ui.activity.self.carMaster;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.CompoundButton;

import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityCarriageInfoPublishBinding;
import com.sgb.kjwl.model.entity.CarInfo;
import com.sgb.kjwl.model.entity.map.CargoMapEntity;
import com.sgb.kjwl.model.entity.self.CarriagePushEntity;
import com.sgb.kjwl.model.entity.self.TypeChooseEntity;
import com.sgb.kjwl.model.entity.transport.CargoPublishEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.InvoiceRateEntity;
import com.sgb.kjwl.model.entity.transport.SingleItemEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.CargoConstant;
import com.sgb.kjwl.utils.PickerHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.utils.VehicleConstant;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.activity.self.AddCarInfoActivity;
import com.sgb.kjwl.view.ui.activity.self.logistics.AddCarActivity;
import com.sgb.kjwl.view.ui.activity.transport.AddSelfCarActivity;
import com.sgb.kjwl.view.ui.activity.transport.SelfCarInfoActivity;
import com.sgb.kjwl.view.ui.adapter.CarriageMoreAdapter;
import com.sgb.kjwl.view.widget.transport.AMapDialog;
import com.sgb.kjwl.viewmodel.self.carMakers.CarriageInfoPublishModel;
import com.sgb.link.entity.AMapAddressEntity;
import com.sgb.link.router.PathLogistics;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.base.model.entity.RequestCode;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.customview.DecimalInputTextWatcher;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.ArrayUtil;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.NumberUtil;
import com.swgk.core.view.areapopup.DefaultUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author: 王彬臣
 * @date:
 * @Description: 推送承运信息
 */
@Route(path = PathLogistics.CarriagePushActivity)
public class CarriageInfoPublishActivity extends AppActivity {
    @Autowired(name = RouterKey.NO, desc = "承运no")
    String mNo;
    @Autowired(name = RouterKey.DATA, desc = "地图货源数据")
    CargoMapEntity mMapData;
    //
    private CarriageInfoPublishModel mViewModel;
    private ActivityCarriageInfoPublishBinding mBinding;
    //是否是开始时间
    private boolean mIsBegin;
    //时间选择器
    private TimePickerView mTimePicker;
    //承运类型选择器
    private OptionsPickerView<GoodsInfoTypeEntity3> mTypePicker;
    //车辆选择器
    private final List<CarInfo> mCarList = new ArrayList<>();
    private OptionsPickerView<CarInfo> mCarPicker;
    //选中车型下标
    private int mSelectCarIndex = -1;
    //是否是装货地
    private boolean mIsLoadPlace;
    //付款约定信息列表
    private List<SingleItemEntity> mMoreList;
    private CarriageMoreAdapter mMoreAdapter;
    //数据实体类
    private CarriagePushEntity mEntity;
    private final List<TypeChooseEntity> radiusBeans = new ArrayList<>();
    private final List<TypeChooseEntity> freightBeans = new ArrayList<>();
    private OptionsPickerView<TypeChooseEntity> radiusPicker;//重量选择器
    private OptionsPickerView<TypeChooseEntity> freightPicker;//重量选择器
    private OptionsPickerView<InvoiceRateEntity> mInvoicePicker;
    int typePos = 2, invoicePos;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        mViewModel = new ViewModelProvider(this).get(CarriageInfoPublishModel.class);
    }

    @Override
    protected void init() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_carriage_info_publish);
        EventBus.getDefault().register(this);
        mBinding.setLifecycleOwner(this);
        mBinding.includeTitle.titleView.setText("货车发布找货需求");
        //取得设置好的drawable对象
        Drawable drawable = this.getResources().getDrawable(R.drawable.check_bg_select);

        //设置drawable对象的大小
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());

        //设置CheckBox对象的位置，对应为左、上、右、下
        mBinding.cbPushConfer.setCompoundDrawables(drawable, null, null, null);
        initPicker();
        initRecycler();
        initEvent();
        initData();

    }

    private void initPicker() {
        mTimePicker = PickerHelper.with(this).getCommonTimeBuild((date, v) -> {
            if (mIsBegin) {
                checkBeginTime(date);
            } else {
                checkEndTime(date);
            }
        })
                .setRangDate(Calendar.getInstance(), null)
                .build();
    }

    private void initRecycler() {
        //更多信息
        mMoreList = new ArrayList<>();
        mMoreAdapter = new CarriageMoreAdapter(mMoreList);
        mBinding.rvPushCarriageMore.setNestedScrollingEnabled(false);
        mBinding.rvPushCarriageMore.setLayoutManager(new LinearLayoutManager(this));
        DividerDecoration.builder(this)
                .colorRes(R.color.transparent)
                .size(12, TypedValue.COMPLEX_UNIT_DIP)
                .showLastDivider()
                .build()
                .addTo(mBinding.rvPushCarriageMore);
        mBinding.rvPushCarriageMore.setAdapter(mMoreAdapter);
    }

    private void initEvent() {
        mBinding.setOnClick(this);
        mBinding.includeTitle.ivBack.setOnClickListener(this);
        mBinding.etPushCarriageFreight.addTextChangedListener(new DecimalInputTextWatcher(mBinding.etPushCarriageFreight, 6, 2));
        mBinding.etPushCarriageFreightDistance.addTextChangedListener(new DecimalInputTextWatcher(mBinding.etPushCarriageFreightDistance, 6, 2));
        mBinding.etPushCarriageDistance.addTextChangedListener(new DecimalInputTextWatcher(mBinding.etPushCarriageDistance, 6, 2));
        //接口回调
        mViewModel.ldType.observe(this, this::syncCarriageType);
        mViewModel.ldCar.observe(this, cars -> syncCarList(cars, false));
        mViewModel.ldRefreshCar.observe(this, cars -> syncCarList(cars, true));
        mViewModel.ldDetail.observe(this, this::syncData);
        mViewModel.ldPush.observe(this, isSuccess -> {
            if (isSuccess) {
                finish();
            }
        });
        mViewModel.ldInvoiceRateEntity.observe(this, this::syncInvoice);
        mBinding.etPushCarriageFreight.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mBinding.etPushCarriageFreight.setBackground(getResources().getDrawable(R.drawable.shape_input_red_bg));
                } else {
                    mBinding.etPushCarriageFreight.setBackground(getResources().getDrawable(R.drawable.shape_input_gray_bg));
                }
            }
        });
        mBinding.etPushCarriageFreightDistance.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mBinding.etPushCarriageFreightDistance.setBackground(getResources().getDrawable(R.drawable.shape_input_red_bg));
                } else {
                    mBinding.etPushCarriageFreightDistance.setBackground(getResources().getDrawable(R.drawable.shape_input_gray_bg));
                }
            }
        });
        mBinding.cbPushConfer.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mBinding.clFreight.setVisibility(View.GONE);
                } else {
                    mBinding.clFreight.setVisibility(View.VISIBLE);
                    //公里数
                    mBinding.etPushCarriageFreightDistance.setText("");
                    //运费
                    mBinding.etPushCarriageFreight.setText("");
                }

            }
        });
    }

    private void initData() {
        mViewModel.getInvoices();
        if (mMapData != null) {
            mViewModel.assemblyMapData(mMapData);
        } else if (TextUtils.isEmpty(mNo)) {
            mEntity = new CarriagePushEntity();
            mEntity.setContacts(UserOperating.getInstance().getUserRealName());
            mEntity.setContactsNumber(UserOperating.getInstance().getPhone());
            //默认选中吨
            mEntity.setFreightUnit(CargoPublishEntity.FreightMode.MODE_WEIGHT);
            //设置数据
            mEntity.setCarrierType(NumberUtil.convertToInt("2"));
            //设置回显
            mBinding.tvPushCarriageType.setText("竞价找货");
            mBinding.tvRadius.setText("10公里内");
            mEntity.setRadius("10000");
            initCommon();
        } else {
            //获取承运详情信息
            mViewModel.getCarriageDetail(this, mNo, false);
        }
        radiusBeans.add(new TypeChooseEntity("0", "不限"));
        radiusBeans.add(new TypeChooseEntity("10000", "10公里内"));
        radiusBeans.add(new TypeChooseEntity("30000", "30公里内"));
        radiusBeans.add(new TypeChooseEntity("50000", "50公里内"));
        radiusBeans.add(new TypeChooseEntity("70000", "70公里内"));
        radiusBeans.add(new TypeChooseEntity("150000", "150公里内"));
        radiusBeans.add(new TypeChooseEntity("100000", "100公里内"));
        radiusBeans.add(new TypeChooseEntity("200000", "200公里内"));

        radiusPicker = PickerHelper.with(this).getCommonPicker(radiusBeans, (options1, options2, options3, v) -> {
            inputRadius(options1);
        });
        radiusPicker.setTitleText("半径");
        radiusPicker.setSelectOptions(1);
        //运费单位
        freightBeans.add(new TypeChooseEntity("0", "元/吨"));
        freightBeans.add(new TypeChooseEntity("1", "元/趟"));
        freightBeans.add(new TypeChooseEntity("2", "元/方"));
        freightPicker = PickerHelper.with(this).getCommonPicker(freightBeans, (options1, options2, options3, v) -> {
            switchFreightMode(options1);
        });
        freightPicker.setTitleText("运费类型");
        freightPicker.setSelectOptions(0);


    }

    /**
     * 设置发票要求
     */
    private void syncInvoice(List<InvoiceRateEntity> list) {
        if (list == null) return;
        setInvoiceInfo(list, 0);
        mInvoicePicker = PickerHelper.with(this).getCommonPicker("选择发票要求", list, (options1, options2, options3, v) -> {
            invoicePos = options1;
            setInvoiceInfo(list, options1);
        });
        mInvoicePicker.setSelectOptions(invoicePos);

    }

    private void setInvoiceInfo(List<InvoiceRateEntity> list, int options1) {
        InvoiceRateEntity entity = list.get(options1);
        //设置数据
        if (!TextUtils.isEmpty(entity.getRate())) {
            mEntity.setRate(entity.getRate());
        }
        if (!TextUtils.isEmpty(entity.getNo())) {
            mEntity.setInvoiceNo(entity.getNo());
        }
        if (!TextUtils.isEmpty(entity.getInvoiceRequest())) {
            mEntity.setInvoice(entity.getInvoiceRequest());
        }
        //设置回显
        mBinding.tvPushCarriageInvoice.setText(com.sgb.kjwl.utils.DefaultUtil.getString(entity.getName()));
    }

    /**
     * 公用预填写信息
     */
    private void initCommon() {
        mBinding.etPushCarriageContact.setText(DefaultUtil.getString(mEntity.getContacts()));
        mBinding.etPushCarriageContactTel.setText(DefaultUtil.getString(mEntity.getContactsNumber()));
        switch (mEntity.getFreightUnit()) {
            case 1:
                switchFreightMode(1);
                break;
            case 2:
                switchFreightMode(0);
                break;
            case 3:
                switchFreightMode(2);
                break;
        }
        //获取选项信息
        mViewModel.getCarriageType();
        mViewModel.getCarInfo(this, false);
    }

    /**
     * 同步数据
     */
    private void syncData(CarriagePushEntity entity) {
        if (entity == null) {
            mEntity = new CarriagePushEntity();
            mEntity.setContacts(UserOperating.getInstance().getUserRealName());
            mEntity.setContactsNumber(UserOperating.getInstance().getPhone());
            //默认选中趟
            mEntity.setFreightUnit(CargoPublishEntity.FreightMode.MODE_ONCE);
            initCommon();
            return;
        }
        mEntity = entity;
        initCommon();
        //承运类型
        mBinding.tvPushCarriageType.setText(CargoConstant.getCarriageType(mEntity.getCarrierType()));
        //车辆信息
        if (!TextUtils.isEmpty(mEntity.getCarNumber())) {
            StringBuilder carBuilder = new StringBuilder();
            carBuilder.append(mEntity.getCarNumber());
            carBuilder.append("/").append(mEntity.getCarTypeName());
            carBuilder.append("/").append(mEntity.getCarLenName());
            carBuilder.append("/").append(NumberUtil.trim0(mEntity.getWeight())).append("吨");
            if (!TextUtils.isEmpty(mEntity.getHeightHurdle())) {
                carBuilder.append("/栏高").append(NumberUtil.trim0(mEntity.getHeightHurdle())).append("米");
            }
            String isDump = VehicleConstant.getIsDumpStr(NumberUtil.convertToInt(mEntity.getIsDump()));
            if (!TextUtils.isEmpty(isDump)) {
                carBuilder.append("/").append(isDump);
            }
            mBinding.tvPushCarriageCar.setText(carBuilder.toString());
        } else {
            mBinding.tvPushCarriageCar.setText("");
        }
        //装卸地
        if (mEntity.getLng() != 0 && mEntity.getLat() != 0) {
            mBinding.tvPushCarriageLoadPlace.setText(String.format("%s%s%s",
                    mEntity.getProvinceName(),
                    mEntity.getCityName(),
                    mEntity.getDistrictName()));
            if (!TextUtils.isEmpty(mEntity.getDetailAddress())) {
                mBinding.etPushCarriageLoadPlace.setText(mEntity.getDetailAddress());
            }
        } else {
            mBinding.tvPushCarriageLoadPlace.setText("");
            mBinding.etPushCarriageLoadPlace.setText("");
        }
        if (mEntity.getDestLng() != 0 && mEntity.getDestLat() != 0) {
            mBinding.tvPushCarriageUnloadPlace.setText(String.format("%s%s%s",
                    mEntity.getDestProvinceName(),
                    mEntity.getDestCityName(),
                    mEntity.getDestDistrictName()));
            if (!TextUtils.isEmpty(mEntity.getDestDetailAddress())) {
                mBinding.etPushCarriageUnloadPlace.setText(mEntity.getDestDetailAddress());
            }
        } else {
            mBinding.tvPushCarriageUnloadPlace.setText("");
            mBinding.etPushCarriageUnloadPlace.setText("");
        }
        //装货时间
        if (!TextUtils.isEmpty(mEntity.getShipmentStartTime())) {
            mBinding.tvPushCarriageBeginTime.setText(DateUtils.stampToDay5(mEntity.getShipmentStartTime()));
            mBinding.tvPushCarriageEndTime.setText(DateUtils.stampToDay5(mEntity.getShipmentEndTime()));
        } else {
            mBinding.tvPushCarriageBeginTime.setText("");
            mBinding.tvPushCarriageEndTime.setText("");
        }
        //运费
        if (!TextUtils.isEmpty(mEntity.getFreight())) {
            mBinding.etPushCarriageFreight.setText(NumberUtil.trim0(mEntity.getFreight()));
        } else {
            mBinding.etPushCarriageFreight.setText("");
        }
        //更多信息
        syncMoreData(mEntity);
    }

    /**
     * 检查设置开始时间
     */
    private void checkBeginTime(Date date) {
        long time = DateUtils.getCustomizeDayMorning(0, date.getTime()).getTime();
        mEntity.setShipmentStartTime(String.valueOf(time));
        mBinding.tvPushCarriageBeginTime.setText(DateUtils.stampToDay5(String.valueOf(time)));
    }

    /**
     * 检查设置结束时间
     */
    private void checkEndTime(Date date) {
        long time = DateUtils.getCustomizeDayNight(0, date.getTime()).getTime();
        mEntity.setShipmentEndTime(String.valueOf(time));
        mBinding.tvPushCarriageEndTime.setText(DateUtils.stampToDay5(String.valueOf(time)));
    }

    /**
     * 设置承运类型
     */
    private void syncCarriageType(List<GoodsInfoTypeEntity3> list) {
        mTypePicker = PickerHelper.with(this).getCommonPicker("选择承运类型", list, (options1, options2, options3, v) -> {
            typePos = options1;
            GoodsInfoTypeEntity3 entity = list.get(options1);
            //设置数据
            mEntity.setCarrierType(NumberUtil.convertToInt(entity.getNo()));
            //设置回显
            mBinding.tvPushCarriageType.setText(DefaultUtil.getString(entity.getName()));
        });
        mTypePicker.setSelectOptions(typePos);
    }

    /**
     * 初始化车辆选择器
     */
    private void syncCarList(List<CarInfo> list, boolean isRefresh) {
        mCarList.clear();
        if (list == null) {
            mBinding.tvPushCarriageCar.setHint("去添加自营车辆");
            mBinding.tvPushCarriageCar.setHintTextColor(getResources().getColor(R.color.color_5892FD));
            return;
        }
        mCarList.addAll(list);
        if (isRefresh) {
            carSelect(list.get(mSelectCarIndex));
        } else {

            if (list.size() == 0) {
                mBinding.tvPushCarriageCar.setHint("去添加自营车辆");
                mBinding.tvPushCarriageCar.setHintTextColor(getResources().getColor(R.color.color_5892FD));
            } else if (list.size() == 1 && list.get(0).getIsComplete() == 1) { //当只有一辆车时，填入默认值
                mSelectCarIndex = 0;
                carSelect(list.get(mSelectCarIndex));
                mBinding.tvPushCarriageCar.setHintTextColor(getResources().getColor(R.color.color_input_text));
            } else {
                mBinding.tvPushCarriageCar.setHintTextColor(getResources().getColor(R.color.color_input_text));
            }
        }
        mCarPicker = PickerHelper.with(this).getCommonPicker("选择车辆", list, (options1, options2, options3, v) -> {
            mSelectCarIndex = options1;
            carSelect(list.get(mSelectCarIndex));
        });
    }

    /**
     * 车辆选择
     */
    private void carSelect(CarInfo car) {

        StringBuilder strBuilder = new StringBuilder();
        if (!TextUtils.isEmpty(car.getCarNumber())) {
            strBuilder.append(car.getCarNumber());
        }
        if (!TextUtils.isEmpty(car.getCarLenName())) {
            strBuilder.append("/").append(car.getCarLenName() + "");
        }
        if (!TextUtils.isEmpty(car.getCarTypeName())) {
            strBuilder.append("/").append(car.getCarTypeName());
        }

        if (car.getWeight() != 0) {
            strBuilder.append("/").append(NumberUtil.trim0(car.getWeight())).append("吨");
            mEntity.setWight(String.valueOf(car.getWeight()));
        }
        if (!TextUtils.isEmpty(car.getHeightHurdle())) {
            strBuilder.append("/栏高").append(NumberUtil.trim0(car.getHeightHurdle())).append("米");
            mEntity.setHeightHurdle(car.getHeightHurdle());
        }
        String isDump = VehicleConstant.getIsDumpStr(car.getIsDump());
        if (!TextUtils.isEmpty(isDump)) {
            strBuilder.append("/").append(isDump);
            mEntity.setIsDump(String.valueOf(car.getIsDump()));
        }
        //设置数据
        mEntity.setDriverNo(car.getNo());
        mEntity.setCarNumber(car.getCarNumber());
        if (car.getIsComplete() == 1) {
            mEntity.setCarLenNo(car.getCarLenNo());
            mEntity.setCarTypeNo(car.getCarTypeNo());
            mBinding.tvPushCarriageCar.setText(strBuilder.toString());
        } else {
            mBinding.tvPushCarriageCar.setText("");
            new RoundDialog.Builder(this)
                    .title("提示")
                    .content("请先完善" + mCarList.get(mSelectCarIndex).getCarNumber() + "的车辆信息")
                    .cancel("暂不完善")
                    .confirm("确定")
                    .confirmCallback(dialog -> {
                        if (UserOperating.getInstance().isPersonal()) {
                            ActivityJump.jumpToActivity(this, AddCarInfoActivity.class, Pair.create("carNo", Long.valueOf(car.getNo())));
                        } else {
                            SelfCarInfoActivity.start(this, Long.valueOf(car.getNo()));
                        }
                    })
                    .show();

        }
    }

    @Override
    public void onClick(View v) {
        closeKeybord();
        if (v == mBinding.includeTitle.ivBack) {
            finish();
        } else if (v == mBinding.tvPushCarriageHistory) {
            //历史承运
            ARouter.getInstance().build(PathLogistics.CarriageHistoryActivity)
                    .navigation(this, RequestCode.CODE_ZERO);
        } else if (v == mBinding.llPushCarriageType) {
            //承运类型
            if (mTypePicker != null) {
                mTypePicker.show();
            }
        } else if (v == mBinding.llPushCarriageCar) {
            //我的车辆

            if (ArrayUtil.isNullOrEmpty(mCarList)) {
                // showAddCarDialog();
                if (UserOperating.getInstance().isPersonal()) {
                    AddCarActivity.start(this);
                } else {
                    AddSelfCarActivity.start(this);
                }
            } else {
                mCarPicker.show();
            }

        } else if (v == mBinding.llPushCarriageLoadPlace) {
            //装货地
            mIsLoadPlace = true;
            AMapDialog.launch(this);
        } else if (v == mBinding.llPushCarriageUnloadPlace) {
            //卸货地
            mIsLoadPlace = false;
            AMapDialog.launch(this);
        } else if (v == mBinding.tvPushCarriageBeginTime) {
            //装货开始时间
            mIsBegin = true;
            mTimePicker.setTitleText("选择装货开始时间");
            mTimePicker.show();
        } else if (v == mBinding.tvPushCarriageEndTime) {
            //装货结束时间
            mIsBegin = false;
            mTimePicker.setTitleText("选择装货结束时间");
            mTimePicker.show();
        } /*else if (v == mBinding.tvPushCarriageOnce) {
            //趟
            switchFreightMode(0);
        } else if (v == mBinding.tvPushCarriageWeight) {
            //吨
            switchFreightMode(1);
        } else if (v == mBinding.tvPushCarriageVolume) {
            //方
            switchFreightMode(2);
        }*/ else if (v == mBinding.llPushCarriageMore) {
            //更多信息
            ARouter.getInstance().build(PathLogistics.EditMoreInfoActivity)
                    .withParcelable(RouterKey.DATA, mEntity)
                    .navigation(this, RequestCode.CODE_ONE);
        } else if (v == mBinding.tvPushCarriageConfirm) {
            clearAllFocus();
            checkData();
        } else if (v == mBinding.llPushRadius) {
            if (radiusPicker != null) {
                radiusPicker.show();
            }
        } else if (v == mBinding.tvPushCarriageFreightSuffix) {
            if (freightPicker != null) {
                freightPicker.show();
            }
        } else if (v == mBinding.llPushCarriageInvoice) {
            if (mInvoicePicker != null) {
                mInvoicePicker.show();
            }
        }
    }

    /**
     * 切换运费类型
     *
     * @param position
     */

    private void switchFreightMode(int position) {
/*        int count = mBinding.llPushCarriageFreightType.getChildCount();
        for (int i = 0; i < count; i++) {
            mBinding.llPushCarriageFreightType.getChildAt(i).setSelected(false);
        }
        mBinding.llPushCarriageFreightType.getChildAt(position).setSelected(true);*/
        //设置运费方式
        switch (position) {
            case 0:
                mEntity.setFreightUnit(CargoPublishEntity.FreightMode.MODE_WEIGHT);
                mBinding.tvPushCarriageFreightSuffix.setText("元/吨");
                break;
            case 1:
                mEntity.setFreightUnit(CargoPublishEntity.FreightMode.MODE_ONCE);
                mBinding.tvPushCarriageFreightSuffix.setText("元/趟");

                break;
            case 2:
                mEntity.setFreightUnit(CargoPublishEntity.FreightMode.MODE_VOLUME);
                mBinding.tvPushCarriageFreightSuffix.setText("元/方");
                break;
        }
    }

    /**
     * 展示添加车辆弹窗
     */
    private void showAddCarDialog() {
        new RoundDialog.Builder(this)
                .title("提示")
                .content("当前无可用车辆，请先添加车辆")
                .cancel("取消")
                .confirm("去添加")
                .confirmCallback(v -> AddCarActivity.start(this))
                .show();
    }

    /**
     * 检查发布数据
     */
    private void checkData() {
        //自选车辆时判断车辆是否完善
        if (mSelectCarIndex != -1) {
            CarInfo carInfo = mCarList.get(mSelectCarIndex);
            if (carInfo != null && carInfo.getIsComplete() != 1) {
                showCompleteCarDialog(carInfo);
                return;
            }
        }
        //设置装卸地详细信息
        mEntity.setDetailAddress(mBinding.etPushCarriageLoadPlace.getText().toString());
        mEntity.setDestDetailAddress(mBinding.etPushCarriageUnloadPlace.getText().toString());


        if (!TextUtils.isEmpty(mBinding.etPushCarriageDistance.getText().toString())) {
            double number = NumberUtil.convertToDouble(mBinding.etPushCarriageDistance.getText().toString());
            if(number<1){
                MToast.showToast(this,"请输入运距要求");
                return;
            }
            if(number>99999){
                MToast.showToast(this,"请输入运距要求");
                return;
            }
            mEntity.setHaulDistance(mBinding.etPushCarriageDistance.getText().toString());
        }


        //公里数
        if (!TextUtils.isEmpty(mBinding.etPushCarriageFreightDistance.getText().toString())) {
            double distance = NumberUtil.convertToDouble(mBinding.etPushCarriageFreightDistance.getText().toString());
            if(distance<1){
                MToast.showToast(this,"请输入意向运费公里数");
                return;
            }
            if(distance>99999){
                MToast.showToast(this,"请输入意向运费公里数");
                return;
            }
            mEntity.setKilometre(mBinding.etPushCarriageFreightDistance.getText().toString());
        }
        if (!TextUtils.isEmpty(mBinding.etCargoQuotationMark.getText().toString())) {
            mEntity.setNote(mBinding.etCargoQuotationMark.getText().toString());
        }
        //设置运费
        if (TextUtils.isEmpty(mBinding.etPushCarriageFreight.getText())) {
            mEntity.setFreight(null);
        } else {
            mEntity.setFreight(NumberUtil.trim0(mBinding.etPushCarriageFreight.getText().toString()));
        }
        //设置联系人
        mEntity.setContacts(mBinding.etPushCarriageContact.getText().toString());
        mEntity.setContactsNumber(mBinding.etPushCarriageContactTel.getText().toString());
        //是否推送信息 1已推送 2未推送
        mEntity.setIsTrue(mBinding.cbPushCarriagePush.isChecked() ? 1 : 2);
        mEntity.setDiscuss(mBinding.cbPushConfer.isChecked() ? 1 : 0);
        mEntity.setPayType("下单先付定金，后货到全款");
        //发布承运
        mViewModel.pushCarriage(this, mEntity);

    }

    /**
     * 展示完善车辆提示
     */
    private void showCompleteCarDialog(CarInfo carInfo) {
        new RoundDialog.Builder(this)
                .title("提示")
                .content(String.format("请先完善%s的车辆信息", carInfo.getCarNumber()))
                .cancel("暂不完善")
                .confirm("确定")
                .confirmCallback(view -> {
                    Intent intent = new Intent(this, AddCarInfoActivity.class);
                    intent.putExtra("carNo", NumberUtil.convertToLong(carInfo.getNo()));
                    startActivity(intent);
                })
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        //地图选择
        if (requestCode == RequestCode.CODE_MAP) {
            AMapAddressEntity entity = AMapDialog.get(data);
            if (mIsLoadPlace) {
                sendAddress(entity);
            } else {
                destAddress(entity);
            }
            return;
        }
        //历史货源回调
        if (requestCode == RequestCode.CODE_ZERO && data != null) {
            //历史承运
            String no = data.getStringExtra(RouterKey.NO);
            mViewModel.getCarriageDetail(this, no, true);
            return;
        }
        if (requestCode == RequestCode.CODE_ONE && data != null) {
            CarriagePushEntity entity = data.getParcelableExtra(RouterKey.DATA);
            syncMoreData(entity);
        }
    }

    /**
     * 发货地址
     */
    private void sendAddress(AMapAddressEntity entity) {
        if (entity == null) return;
        mEntity.setLat(entity.getLatitude());
        mEntity.setLng(entity.getLongitude());
        mEntity.setProvinceName(entity.getProvince());
        mEntity.setProvinceNo(entity.getProvinceNo());
        mEntity.setCityName(entity.getCity());
        mEntity.setCityNo(entity.getCityNo());
        mEntity.setDistrictName(entity.getDistrict());
        mEntity.setDistrictNo(entity.getDistrictNo());
        mEntity.setDetailAddress(entity.getSnippet());
        //设置页面
        mBinding.tvPushCarriageLoadPlace.setText(String.format("%s%s%s",
                entity.getProvince(),
                entity.getCity(),
                entity.getDistrict()));
        mBinding.etPushCarriageLoadPlace.setText(entity.getSnippet());
        mBinding.etPushCarriageLoadPlace.setVisibility(View.VISIBLE);
    }

    /**
     * 目的地地址
     */
    private void destAddress(AMapAddressEntity entity) {
        if (entity == null) return;
        mEntity.setDestLat(entity.getLatitude());
        mEntity.setDestLng(entity.getLongitude());
        mEntity.setDestProvinceName(entity.getProvince());
        mEntity.setDestProvinceNo(entity.getProvinceNo());
        mEntity.setDestCityName(entity.getCity());
        mEntity.setDestCityNo(entity.getCityNo());
        mEntity.setDestDistrictName(entity.getDistrict());
        mEntity.setDestDistrictNo(entity.getDistrictNo());
        mEntity.setDestDetailAddress(entity.getSnippet());
        //设置页面
        mBinding.tvPushCarriageUnloadPlace.setText(String.format("%s%s%s",
                entity.getProvince(),
                entity.getCity(),
                entity.getDistrict()));
        mBinding.etPushCarriageUnloadPlace.setText(entity.getSnippet());
        mBinding.etPushCarriageUnloadPlace.setVisibility(View.VISIBLE);
    }

    /**
     * 同步更多信息
     */
    private void syncMoreData(CarriagePushEntity entity) {
        if (entity == null) return;
        mEntity = entity;
        //更多信息
        if (!TextUtils.isEmpty(mEntity.getPayType())
                || !TextUtils.isEmpty(mEntity.getRate())
                || mEntity.getBargain() != null
                || !TextUtils.isEmpty(mEntity.getInvoice())
                || !TextUtils.isEmpty(mEntity.getNote())) {
            mMoreList.clear();
            mMoreList.add(new SingleItemEntity("付款方式", DefaultUtil.getString(mEntity.getPayType(), "/")));
            //发票要求信息匹配检测
            if (mEntity.isInvoiceChanges()) {
                mEntity.setInvoiceNo("");
                mEntity.setInvoice("");
                mEntity.setRate("");
                showFieldAlterDialog();
                mMoreList.add(new SingleItemEntity("发票要求", "/"));
            } else if (!TextUtils.isEmpty(mEntity.getInvoice()) && mEntity.getRate() != null && !TextUtils.isEmpty(mEntity.getInvoiceNo())) {
                if ("不开发票".equals(mEntity.getInvoice())) {
                    mMoreList.add(new SingleItemEntity("发票要求", entity.getInvoice()));
                } else {
                    String invoiceStr = NumberUtil.trim0(mEntity.getRate()) + "%" + mEntity.getInvoice();
                    mMoreList.add(new SingleItemEntity("发票要求", invoiceStr));
                }
            } else {
                mMoreList.add(new SingleItemEntity("发票要求", "/"));
            }
            if (mEntity.getBargain() == null) {
                mMoreList.add(new SingleItemEntity("可否议价", "/"));
            } else {
                mMoreList.add(new SingleItemEntity("可否议价", mEntity.getBargain() == 1 ? "可议价" : "不可议价"));
            }
            mMoreList.add(new SingleItemEntity("备\u3000\u3000注", DefaultUtil.getString(mEntity.getNote(), "/")));
            mMoreAdapter.notifyDataSetChanged();
            //
            mBinding.tvPushCarriageMore.setHint("");
            mBinding.rvPushCarriageMore.setVisibility(View.VISIBLE);
        } else {
            mBinding.tvPushCarriageMore.setHint("付款方式、发票、税率、备注（选填）");
            mBinding.rvPushCarriageMore.setVisibility(View.GONE);
        }
    }

    /**
     * 发票要求字段调整，提示用户重新选择
     */
    private void showFieldAlterDialog() {
        new RoundDialog.Builder(this)
                .title("提示")
                .content("平台发票要求已调整，使用历史承运发布需重新选择该信息")
                .confirm("我知道了")
                .singleBtn(true)
                .confirmCallback(v -> {
                    if (mEntity != null) {
                        mEntity.setInvoiceChanges(false);
                    }
                })
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .show();
    }

    /**
     * 录入半径
     */
    private void inputRadius(int options) {
        if (radiusBeans.size() >= options + 1) {
            TypeChooseEntity entity = radiusBeans.get(options);
            //重量
            String radiusStr = "";
            if (entity != null) {
                radiusStr = entity.getName();
            }
            if (TextUtils.isEmpty(radiusStr)) {
                mBinding.tvRadius.setText("不限");
            } else {
                mBinding.tvRadius.setText(radiusStr.trim());
            }
            mEntity.setRadius(entity.getNo());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LogisticsEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CARINFO_COMMIT) {//完善车辆信息后回调
            mViewModel.getCarInfo(this, true);
        }
    }
}
